// VirtualCommentList.tsx
import { useState, useEffect } from 'react';
import type { FC } from 'react';
import { FixedSizeList as List } from 'react-window';
import './style/Ping.css';
import React from 'react'
import { useLocation, useNavigate } from 'react-router-dom'
import { ArrowLeft, LikeO, YouzanShield } from '@react-vant/icons';
import './style/DetailCar.css'
import axios from 'axios'
import { addLists } from '../store/modules/cart'
import { Popup, Space, Button, Stepper, Toast } from 'react-vant'
import { useDispatch } from 'react-redux'
import { add } from '../store/modules/cart'

// 评论数据类型定义
interface Comment {
    id: number;
    userName: string;
    avatar: string;
    time: string;
    content: string;
    rating: number;
}

interface Collection {
    _id: string;
    name: string;
    img: string;
}

interface Product {
    id: number;
    title: string;
    content: string;
    price: number;
    image: string;
}

// 生成模拟评论数据
const generateComments = (count: number): Comment[] => {
    const productTypes = ['精华', '面霜', '面膜', '爽肤水', '乳液', '眼霜', '防晒霜'];
    const positiveAdjectives = ['非常好用', '效果明显', '温和不刺激', '吸收很快', '会回购', '质地清爽', '保湿效果好', '不油腻'];
    const negativeAdjectives = ['一般般', '效果不明显', '有点刺激', '吸收较慢', '不会回购', '质地厚重', '保湿一般', '有点油腻'];
    const benefits = [
        '保湿效果持久', '肤色明显提亮', '毛孔细致了', '皮肤更光滑',
        '细纹减少了', '皮肤更有弹性', '肤色更均匀', '痘痘减少了',
        '敏感改善了', '皮肤更水润', '黑眼圈淡化了', '皮肤更紧致'
    ];
    const timeUnits = ['分钟', '小时', '天', '周', '月'];
    const userNames = [
        '护肤达人', '美妆博主', '敏感肌', '油皮星人', '干皮救星',
        '混合肌', '痘痘肌', '熟龄肌', '学生党', '上班族'
    ];

    return Array.from({ length: count }, (_, i) => {
        const isPositive = Math.random() > 0.2; // 80% 正面评价
        const adjectives = isPositive ? positiveAdjectives : negativeAdjectives;
        const rating = isPositive ? Math.floor(Math.random() * 2) + 4 : Math.floor(Math.random() * 2) + 1; // 正面评价4-5星，负面评价1-2星
        
        // 生成随机时间
        const timeValue = Math.floor(Math.random() * 30) + 1;
        const timeUnit = timeUnits[Math.floor(Math.random() * timeUnits.length)];
        const time = `${timeValue}${timeUnit}前`;

        // 生成随机用户名
        const userName = `${userNames[Math.floor(Math.random() * userNames.length)]}${String(i + 1).padStart(4, '0')}`;

        // 生成评论内容
        const productType = productTypes[Math.floor(Math.random() * productTypes.length)];
        const adjective = adjectives[Math.floor(Math.random() * adjectives.length)];
        const benefit = benefits[Math.floor(Math.random() * benefits.length)];
        const content = `这款${productType}使用体验${adjective}，${benefit}。${isPositive ? '推荐购买！' : '建议谨慎购买。'}`;

        return {
            id: i + 1,
            userName,
            avatar: `https://picsum.photos/50/50?random=${i}`,
            time,
            content,
            rating
        };
    });
};

// 星星评分组件
const StarRating: FC<{ rating: number }> = ({ rating }) => {
    return (
        <div className="star-rating">
            {[...Array(5)].map((_, index) => (
                <span
                    key={index}
                    className={`star ${index < rating ? 'filled' : ''}`}>★</span>
            ))}
        </div>
    );
};

// 评论项组件
const CommentItem: FC<{
    index: number;
    style: React.CSSProperties;
    data: Comment[];
}> = ({ index, style, data }) => {
    const comment = data[index];

    return (
        <div style={style} className="comment-item">
            <div className="comment-header">
                <img
                    src={comment.avatar}
                    alt={comment.userName}
                    className="avatar" />
                <div className="user-info">
                    <div className="user-name">{comment.userName}</div>
                    <div className="comment-meta">
                        <span className="time">{comment.time}</span>
                        <StarRating rating={comment.rating} />
                    </div>
                </div>
            </div>
            <p className="comment-content">{comment.content}</p>
        </div>
    );
};

// 主组件
export default function Detail() {
    const comments = generateComments(50);
    const itemHeight = 160;
    const location = useLocation()
    const navigate = useNavigate()
    const data = location.state as Product
    const [visible1, setVisible1] = useState(false)
    const [list, setList] = useState<Collection[]>([])
    const dispatch = useDispatch()
    const [quantity, setQuantity] = useState(1)
    const [active, setActive] = useState(-1)
    const [cateid, setcateid] = useState('')

    const getlist = async () => {
        const res = await axios.get(`http://localhost:3000/list`)
        setList(res.data.list)
    }

    useEffect(() => {
        getlist()
    }, [])

    const addList = async () => {
        if (!cateid) {
            alert('请选择收藏夹')
            return
        }
        dispatch(addLists({...data, cateid}))
        setVisible1(false)
        alert('收藏成功')
    }

    const handleAddToCart = () => {
        dispatch(add({...data, num: quantity, flag: false}))
        alert('已加入购物车')
        navigate('/car')
    }

    return (
        <div className="detail-page">
            <div className="detail-header">
                <ArrowLeft onClick={() => navigate('/app/shou')} />
                <h2>商品详情</h2>
                <LikeO onClick={() => setVisible1(true)} />
            </div>

            <div className="detail-content">
                <div className="product-gallery">
                    <img src={data.image} alt={data.name} />
                </div>

                <div className="product-info">
                    <div className="product-header">
                        <h1 className="product-title">{data.name}</h1>
                        <div className="product-price">¥{(data.price / 10).toFixed(2)}</div>
                    </div>

                    <div className="product-specs">
                        <span className="spec-item">规格: 5.60 F 盎司/100 毫升</span>
                        <Button type="danger" size="small" onClick={handleAddToCart}>
                            加入购物车
                        </Button>
                    </div>
                </div>

                <div className="product-description">
                    <h3>产品介绍</h3>
                    <p>{data.description}</p>
                </div>

                <div className="product-comments">
                    <div className="comments-header">
                        <h3>用户评价</h3>
                        <div className="comments-verified">
                            <YouzanShield />
                            <span>所有评论均来自经过验证的买家</span>
                        </div>
                    </div>
                    <div className="comment-list-container">
                        <List
                            height={600}
                            itemCount={comments.length}
                            itemSize={itemHeight}
                            width="100%"
                            itemData={comments}>
                            {CommentItem}
                        </List>
                    </div>
                </div>
            </div>

            <Popup
                visible={visible1}
                position="bottom"
                round
                onClose={() => setVisible1(false)}>
                <div className="collection-popup">
                    <h3>选择收藏夹</h3>
                    <div className="collection-grid">
                        {list.map((item, index) => (
                            <div
                                key={item._id}
                                className={`collection-item ${active === index ? 'selected' : ''}`}
                                onClick={() => {
                                    setActive(index)
                                    setcateid(item._id)
                                }}>
                                <img src={item.img} alt={item.name} />
                                <span>{item.name}</span>
                            </div>
                        ))}
                    </div>
                    <Button type="primary" block onClick={addList}>
                        确定
                    </Button>
                </div>
            </Popup>
        </div>
    )
}